package Z.dailyExercise.March;

public class _2两数相加 {


    /**
     * 自解：逆序刚好与计算顺序相同 需要额外一个变量计算进为
     *
     * 非常耗时
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = new ListNode(0);
        boolean isAdd = false;
        ListNode temp = null;
        if (l1.val + l2.val>=10){
            isAdd = true;
           temp = new ListNode((l1.val + l2.val)%10);

        }else {
            temp = new ListNode(l1.val + l2.val);
        }

        res.next = temp;
        l1= l1.next;
        l2 = l2.next;
        int num =0;


        while (l1 != null && l2 != null){
            if (isAdd){
                num = l1.val + l2.val+1;
                if (num >= 10){
                    num %= 10;
                }else {
                    isAdd = false;
                }
            }else {
                num = l1.val + l2.val;
                if (num >= 10){
                    num %= 10;
                    isAdd = true;
                }
            }
            temp.next = new ListNode(num);
            temp = temp.next;
            l1= l1.next;
            l2 = l2.next;

        }

        while (l1 != null){
            if (isAdd){
                num = l1.val+1;
                if (num >= 10){
                    num %= 10;
                }else {
                    isAdd = false;
                }
                temp.next = new ListNode(num);
                temp = temp.next;
                l1 = l1.next;

            }else {
                temp.next = l1;
                break;
            }
        }
        while (l2!= null){
            if (isAdd){
                num = l2.val+1;
                if (num >= 10){
                    num %= 10;
                }else {
                    isAdd = false;
                }
                temp.next = new ListNode(num);
                temp = temp.next;
                l2 = l2.next;

            }else {
                temp.next = l2;

                break;
            }
        }

        if (isAdd){
            temp.next = new ListNode(1);
            temp = temp.next;

        }

        return res.next;



    }

    //标准写法
    public ListNode addTwoNumbers1(ListNode l1, ListNode l2){
        ListNode root = new ListNode(0);
        ListNode cursor = root;
        int carry = 0;
        //只有当两个表均结束并且咩有进位才结束
        while (l1 != null || l2 != null || carry != 0) {
            int l1val = l1 != null ? l1.val : 0;
            int l2val = l2 != null ? l2.val : 0;
            int sum = l1val + l2val + carry;
            carry = sum / 10;

            ListNode sumNode = new ListNode(sum % 10);
            cursor.next = sumNode;
            cursor = sumNode;

            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        return root.next;

    }

}
